package com.financing.controller.app;
import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import com.financing.model.Data;
import com.financing.model.app.AppPromotion;
import com.financing.model.app.AppVersion;
import com.financing.model.user.User;
import com.financing.service.app.AppPromotionService;
import com.financing.service.app.AppVersionService;
import com.financing.service.user.UserService;
import com.financing.util.AES;
import com.financing.util.Http;
import com.financing.util.Json;
import com.financing.util.Str;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;

/**
 * APP控制器
 * @author 无处不在的二叔
 */
public class AppController extends Controller {
	private static UserService user = new UserService();
	private static AppVersionService appVersion = new AppVersionService();
	private static AppPromotionService appPromotion = new AppPromotionService();

	@Clear
	public void index() throws Exception { 
		render("index.html"); 
	}
	
	/**
	 * app页面控制器
	 */
	@Clear 
	@Before({SessionInViewInterceptor.class})
	public void page() throws Exception {
		String page = getPara(0); 
		String page2 = getPara(1); 
		setAttr("para",getParaMap());
		if(Str.nb(page2)){
			render(page+"/"+page2+".html");
		}else{
			render(page+".html");
		}
	} 
	
	/**
	 * APP版本检查
	 */
	@Clear 
	public void version() throws Exception {
		String system = getPara("system");
		String type = getPara("type");
		String code = getPara("code");
		AppVersion version = appVersion.checkVersion(system, type, code);
		if(version!=null && Str.nb(version.getStr("code"))){
			renderJson(Json.ok("检测到新版本！", Data.put("version", version)));
		}else{
			renderJson(Json.error("已是最新版本！"));
		}
	} 
	
	/**
	 * APP版本参数设置
	 */
	@Clear
	public void setVersion() throws Exception {
		
		int id = getParaToInt("id", 0);
		AppVersion version = id>0 ? AppVersion.me.findById(id) : new AppVersion();
		version.setName(getPara("name"));
		version.setCode(getPara("code"));
		version.setUrl(getPara("url"));
		version.setSummary(getPara("summary"));
		version.setIsForce(getParaToInt("isForce"));
		version.setSystem(getPara("system"));
		version.setType(getPara("type"));
		
		if(id>0 ? version.update() : version.setCreateTime(new Date()).save()){
			renderJson(Json.ok("数据保存成功！"));
		}else{
			renderJson(Json.error("数据保存失败！"));
		}
	} 
	
	/**
	 * 获取APP版本信息
	 */
	@Clear
	public void versionInfo() throws Exception {
		renderJson(Json.ok("数据获取成功！", AppVersion.me.findById(getParaToInt("id",0))));
	} 
	
	/**
	 * 获取APP版本列表信息
	 */
	@Clear
	public void versionList() throws Exception {
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		renderJson(Json.ok("数据获取成功！", Data.put("page",appVersion.list(page,size,Data.flat(getParaMap())))));
	} 
	
	/**
	 * APP推广接口
	 * @throws Exception
	 */
	@Clear 
	public void promotion() throws Exception {
		
		// 获取参数
		String type = getPara("type", "reg");
		String app = getPara("app","1125302212");
		String idfa = getPara("idfa");
		String url = getPara("callbackurl");
		
		// 初始化返回值
		JSONObject json = new JSONObject();
		json.put("success",true);
		json.put("message", "成功");
		
		AppPromotion ap = new AppPromotion();
		ap = appPromotion.findByIdfa(app,idfa);
		
		if(Str.nb(app) && Str.nb(idfa)) {
			if(Str.eq("reg", type)) {
				if(ap==null) {
					if(Str.nb(url)) {
						ap = new AppPromotion();
						ap.setApp(app);
						ap.setUdid(getPara("udid"));
						ap.setIdfa(idfa);
						ap.setOpenudid(getPara("openudid"));
						ap.setOs(getPara("os"));
						ap.setIp(getPara("ip"));
						ap.setCallbackurl(url);
						ap.setCreateTime(new Date());
						ap.setStatus("create");
						ap.save();
					} else {
						json.put("success",false);
						json.put("message", "callbackurl不可为空！");
					}
				} else {
					json.put("success",false);
					json.put("message", "idfa数据已存在！");
				}
			} else if(Str.eq("active", type)) {
				String mobile = AES.decode(getPara("mobile"));
				User u = user.findByMobile(mobile);
				if(u!=null && ap!=null && Str.ne("success", ap.getStatus())) {
					int count = 0;
					json.put("success",false);
					json.put("message", "回调失败！");
					ap.setStatus("failed");
					ap.setUserId(u.getId());
					ap.setMobile(u.getMobile());
					try{
						do {
						    Thread.sleep(5000);//暂停5秒后程序继续执行
							count++; 
							json = Http.post(ap.getCallbackurl(), json);
							if(Str.nb(json.toJSONString()) && Str.eq("true", json.getString("success"))) {
								ap.setStatus("success").setCallbackTime(new Date()).update();
								json.put("message", "激活成功！");
								u.setPopChannel("0018").update();
							}
						}while(Str.eq("false", json.getString("success")) && count<=3);
					}catch (InterruptedException e) {
					    e.printStackTrace();
					}
					ap.update();
				} else {
					json.put("success",false);
					json.put("message", "数据对象不存在！");
				}
			}
		} else {
			json.put("success",false);
			json.put("message", "app或idfa不可为空！");
		}
		renderJson(json);
	}
	
	
	/**
	 * APP推广接口
	 * @throws Exception
	 */
	@Clear 
	public void query() throws Exception {
		
		// 获取参数
		String idfa = getPara("idfa");
		
		// 初始化返回值
		JSONObject json = new JSONObject();
		json.put(idfa,"0");	
		
		if(Str.nb(idfa)) {
			AppPromotion ap = appPromotion.findByIdfa("1125302212",idfa);
			if(ap!=null) {
				json.put(idfa,"1");	
			}
		}
		renderJson(json);
	}
}